package com.example.controller;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.example.framwork.code.CodeConst;
import com.example.framwork.code.CommanHead;
import com.example.framwork.exception.BusinessLogicException;
import com.example.framwork.result.ProjectResult;
import com.example.springsecrity.JwtUtil;
import com.example.springsecrity.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/sec")
public class SecLogin {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //登录操作
    @RequestMapping("/login")
    public ProjectResult login(String username, String password, HttpServletResponse response) {


        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToke = new UsernamePasswordAuthenticationToken(username, password);
        try {
            Authentication authentication = authenticationManager.authenticate(usernamePasswordAuthenticationToke);
            if (authentication == null) {
                throw new BusinessLogicException("账号密码错误");

            }

            LoginUser loginUser = (LoginUser) authentication.getPrincipal();

            stringRedisTemplate.opsForValue().set(CommanHead.RedisLoginUer + loginUser.getUsername(), JSONUtil.toJsonStr(loginUser), CommanHead.nRedisMin, TimeUnit.MINUTES);
            String token = JwtUtil.createJWT(loginUser.getUsername());
            return new ProjectResult(CodeConst.SUCCESS, "登陆成功", token);


        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                throw new BusinessLogicException("账号密码错误");
            } else if (e instanceof UsernameNotFoundException) {
                throw new BusinessLogicException("用户不存在");
            }
        }
        return new ProjectResult(CodeConst.FAILED, "登陆成功");
    }

    @RequestMapping("/adminUserGet")
    @PreAuthorize("hasAnyAuthority('admin','user')")
    public ProjectResult adminUserGet() {
        return new ProjectResult(CodeConst.SUCCESS, "admin--user--ok");
    }

    //登录操作
    @RequestMapping("/adminGet")
    @PreAuthorize("hasAnyAuthority('admin')")
    public ProjectResult adminGet() {
        return new ProjectResult(CodeConst.SUCCESS, "admin--ok");
    }

    //登录操作
    @RequestMapping("/userGet")
    @PreAuthorize("hasAnyAuthority('user')")
    public ProjectResult userGet() {
        return new ProjectResult(CodeConst.SUCCESS, "user--ok");
    }

    @RequestMapping("/any")
    public ProjectResult any() {
        return new ProjectResult(CodeConst.SUCCESS, "any--ok");
    }

    @RequestMapping("/logout")
    public ProjectResult login() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser user = (LoginUser) authentication.getPrincipal();

        stringRedisTemplate.delete(CommanHead.RedisLoginUer + user.getUsername());
        return new ProjectResult(CodeConst.SUCCESS, "退出成功");
    }
}
